package org.winexpress


import grails.converters.deep.JSON
import org.codehaus.groovy.grails.web.json.JSONObject;
import org.codehaus.groovy.grails.web.json.JSONArray;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;


class CustomerManagementController {
    
    // initialization: GSP support operations (must be same as GSP filename)
    def memberRegistration = {
        // consume winexpress server web service
        def txt = new URL("http://localhost:8080/WineXpress/country").text
        
         if (txt.getAt(0) == '{') {
            JSONObject o = new JSONObject(txt)
            if (o.has("404")) {
                if (o.get("404") == true) {
                    flash.message = 'No countries.<br/><br/>'
                    try {
                        redirect(uri:"/404")
                    }
                    catch (CannotRedirectException) {
                        println 'already redirected...'
                    }
                }
            }
        }
        else {
            JSONArray arr  = new JSONArray(txt)
            ArrayList<Country> countryList = new ArrayList<Country>()

            arr.each()
            {
                Country c = new Country()
                c.countryName = it.countryName
                c.id = it.id
                countryList.add(c)
            }
    //        countryList.each()
    //        {
    //            println it
    //        }

            [countries:countryList]
        }
    }
    
    // incorporates view and other buttons
    def memberInfoManagement = {
        def customerId = session.customerId
        
        // consume winexpress server web service
        def txtCustomer = new URL("http://localhost:8080/WineXpress/customer/" + customerId).text
        println txtCustomer
        
        // todo: either package as customer or convert only birthdate
        JSONObject objCustomer = new JSONObject(txtCustomer)
        
//        HttpResponse response = txtCustomer
//        if (response.toString().equals("404")) {
//            println 'it is 404.'
//        }
        
        if (objCustomer.has("404")) {
            if (objCustomer.get("404") == true) {
                flash.message = 'Customer not found. Please try again later.<br/><br/>'

                redirect(uri:"/")
            }
        }
        else {
            IntRange indexRange = new IntRange(0,9)
            def ll = objCustomer.lastLogin.getAt(indexRange)
            def bd = objCustomer.birthdate.getAt(indexRange)

            // consume winexpress server web service
            def txtCountry = new URL("http://localhost:8080/WineXpress/country/" + objCustomer.countryId).text

            JSONObject objCountry = new JSONObject(txtCountry)
            def countryName = objCountry.countryName

            [customer:objCustomer, countryName:countryName, lastLogin:ll, birthdate:bd]
        }
    }
    
    def memberInfoEditing = {
        def customerId = session.customerId
        
        // consume winexpress server web service
        def txt = new URL("http://localhost:8080/WineXpress/country").text
        
        JSONArray arr  = new JSONArray(txt)
        ArrayList<Country> countryList = new ArrayList<Country>()
    
        arr.each()
        {
           Country c = new Country()
           c.countryName = it.countryName
           c.id = it.id
           countryList.add(c)
        }
        
        
        // consume winexpress server web service
        def txtCustomer = new URL("http://localhost:8080/WineXpress/customer/" + customerId).text
        
        // todo: either package as customer or convert only birthdate
        JSONObject objCustomer = new JSONObject(txtCustomer)
//        println "editAccountInformation >> Customer Retrieved: " + objCustomer.id + " " + objCustomer.lastName + " " + objCustomer.firstName
        IntRange indexRange = new IntRange(0,9)
        def ll = objCustomer.lastLogin.getAt(indexRange)
        def bd = objCustomer.birthdate.getAt(indexRange)
        
        // consume winexpress server web service
        def txtCountry = new URL("http://localhost:8080/WineXpress/country/" + objCustomer.countryId).text
        
        JSONObject objCountry = new JSONObject(txtCountry)
        def countryName = objCountry.countryName
        
//        println "frontend country name : " + countryName

        println "editAccountInformation OK"
        
        [customer:objCustomer, countryName:countryName, lastLogin:ll, birthdate:bd, countries:countryList]
    }
    
    
    
    
    
    // REST-related operations for accessing WineXpress Server (for clearer view only)
    // GET
    def show = {
        
    }
    
    // PUT
//    def updateMemberLastLogin = {
//        def id = session.customerId
//        // create a JSONObject to send to winexpress server
//        JSONObject o = new JSONObject()
//        o.put("id",id)
//        
//        // to create use PUT
//        HttpClient httpclient = new DefaultHttpClient()
//        HttpResponse response
//        // consume winexpress server web service
//        HttpPut httpput = new HttpPut("http://localhost:8080/WineXpress/customer") // WineXpress Server's URI
//        StringEntity se = new StringEntity(o.toString())     
//        httpput.setEntity(se);          
//        response = httpclient.execute(httpput);
//        
//        println "updateMemberLastLogin OK"
//    }
    
    def updateMemberDetails = {
        def id = session.customerId
        def password = params['password']
        def newpassword = params['newpassword']
        def confirmpassword = params['confirmpassword']
        def email = params['email']
        def blkHouseNo = params['blkHouseNo']
        def streetName = params['streetName']
        def unitNo = params['unitNo']
        def postalCode = params['postalCode']
        def country = params['country']
        def telNo = params['telNo']
        
        // consume winexpress server web service
//        def txtCountry = new URL("http://localhost:8080/WineXpress/country?countryName=" + country).text
//        
//        JSONObject objCountry = new JSONObject(txtCountry)
//        def countryId = objCountry.countryId
        
        
        // create a JSONObject to send to winexpress server
        JSONObject o = new JSONObject()
        o.put("id",id)
        o.put("password",newpassword)
        o.put("email",email)
        o.put("blkHouseNo",blkHouseNo)
        o.put("streetName",streetName)
        o.put("unitNo",unitNo)
//        o.put("countryId",countryId)
        o.put("postalCode",postalCode)
        o.put("country",country)
        o.put("telNo",telNo)
        
        
        // to create use PUT
        HttpClient httpclient = new DefaultHttpClient()
        HttpResponse response
        // consume winexpress server web service
        HttpPut httpput = new HttpPut("http://localhost:8080/WineXpress/customer") // WineXpress Server's URI
        StringEntity se = new StringEntity(o.toString())     
        httpput.setEntity(se);          
        response = httpclient.execute(httpput);
        
        println "updateMemberDetails OK"
        
        flash.message = "Account details have been successfully updated."
        
        redirect(uri:"/memberInfoManagement")
    }
    
    // DELETE
    def delete = {
        
    }
    
    // POST
    def postCreateMember = {
        // get form values
        def username = params['username']        
        def lastName = params['lastName']        
        def firstName = params['firstName']
        def birthdate = params['birthdate']
        def email = params['email']
        def blkHouseNo = params['blkHouseNo']
        def streetName = params['streetName']
        def unitNo = params['unitNo']
        def country = params['country']
        def postalCode = params.postalCode
        def telNo = params.telNo
        
        def dobDay = params['dobDay']
        def dobMonth = params['dobMonth']
        def dobYear = params['dobYear']
        
        def dob = dobDay+"-"+dobMonth+"-"+dobYear
        // conversions
        Date bd = Date.parse("dd-MM-yyyy",dob)
        
        // create a JSONObject to send to winexpress server
        JSONObject o = new JSONObject()
        o.put("username",username)
        o.put("lastName",lastName)
        o.put("firstName",firstName)
        o.put("birthdate",bd)
        o.put("email",email)
        o.put("blkHouseNo",blkHouseNo)
        o.put("streetName",streetName)
        o.put("unitNo",unitNo)
        o.put("country",country)
        o.put("postalCode",postalCode)
        o.put("telNo",telNo)
        
        // to create use POST
        HttpClient httpclient = new DefaultHttpClient()
        HttpResponse response
        // consume winexpress server web service
        HttpPost httppost = new HttpPost("http://localhost:8080/WineXpress/customer") // WineXpress Server's URI
        StringEntity se = new StringEntity(o.toString())          
        httppost.setEntity(se);          
        response = httpclient.execute(httppost);
        
        // get response code
        StatusLine status = response.getStatusLine()
        int statusCode = status.getStatusCode()
        
        println statusCode
        if (statusCode == 201) {
            flash.message = "Account successfully created. Please check your email for activation mail."
            redirect(uri:"/thankyou")
        }
        if (statusCode == 400) {
            flash.message = "Account could not be created. Please try again."
            redirect(uri:"/memberRegistration")
        }
        if (statusCode == 406) {
            flash.message = "This username has already been taken."
            redirect(uri:"/memberRegistration")
        }
    }
    
}
